/*!
 * vinculum
 * Copyright(c) 2017 azzly
 * MIT Licensed
 */
 
'use strict';

/**
 * Module dependencies.
 * @private
 */
const helper = require("./helper");
const cache = require("./cache");
const debug = require("./debug")(__filename);

const _session_user_name = 'user';
const _session_user_roles_name = 'user_roles';

class session{
  constructor(sessionKey){
    this.sessionData = {createtime:Date.now()};
    this.inited = false;
    this.changed = true;
    this.sessionKey = sessionKey;
  }
  
  clear(){
    this.sessionData = {createtime:Date.now()};
    return this.save();
  }
  
  getUser(){
    return this.get(_session_user_name) || {};
  }
  
  setUser(value){
    if(value) this.set(_session_user_name,value);
  }
  
  getUserRoles(){
    return this.get(_session_user_roles_name) || [];
  }
  
  setUserRoles(value){
    if(value) this.set(_session_user_roles_name,value);
  }
  
  get(name){
    if(this.inited){
      return this.sessionData[name];
    }else{
      return null;
    }
  }
  
  set(name,value){
    if(this.inited){
      this.changed = true;
      this.sessionData[name] = value;
    }
  }
  
  init(){
    return new Promise((resolve, reject)=>{
      cache.getSession(this.sessionKey).then(result=>{
        this.inited = true;
        this.sessionData = result;
        resolve();
      }).catch(err=>{
        reject(err);
      });
    });
  }
  
  save(){
    if(this.inited){
      if(this.changed){
        return cache.setSession(this.sessionKey,this.sessionData);
      }else{
        return Promise.resolve();
      }
    }else{
      return Promise.reject();
    }
  }
}

module.exports = session;